package charlie.shop.admin;

import com.charlie.beans.Groups;
import com.charlie.db.DAOLocal;
import com.charlie.sessions.GroupsFacadeLocal;
import com.charlie.sessions.GroupsRolesFacadeLocal;
import com.charlie.sessions.RolesFacadeLocal;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Delete group servlet
 *
 * @author Оленка
 */
@WebServlet(name = "DeleteGroup", urlPatterns = {"/admin/deleteGroup"})
public class DeleteGroup extends HttpServlet {

    @EJB
    GroupsFacadeLocal groupsFacade;
    @EJB
    DAOLocal dao;
    @EJB
    RolesFacadeLocal rolesFacade;
    @EJB
    GroupsRolesFacadeLocal groupsRolesFacade;
    String id;
    Groups group;

    /**
     * Delete selected group
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (group != null) {
            List<String> roles = dao.getGroupRolesNamesList(group.getGroupsId());
            try {
                for (String r : roles) {
                    dao.deleteGroupsRole(group.getGroupsId(), rolesFacade.findByRolesName(r).getRolesId());
                }
                dao.deleteUsersGroups(group.getGroupsId());
            } catch (SQLException ex) {
                Logger.getLogger(DeleteGroup.class.getName()).log(Level.SEVERE, null, ex);
            }
            groupsFacade.remove(group);
        }
        getServletContext().getRequestDispatcher("/admin/completeDeletion.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        id = request.getParameter("groupId");
        group = groupsFacade.findByGroupsId((Integer.valueOf(id)));
        request.setAttribute("group", group);
        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/admin/deletion.jsp").forward(request, response);
    }
}
